<?php

class ScoreManager_StageInputController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $this->view->yearSemester = $this->getRequest()->getPost('yearSemester');
        $this->view->classSn = $this->getRequest()->getPost('classSn');
        $this->view->subjectSn = $this->getRequest()->getPost('subjectSn');
        $this->view->stage = $this->getRequest()->getPost('stage');
        if ($this->view->classSn) {
            $this->view->subjectData = $this->_getSubject();
            $this->_getScore();
        }

    }

    /**
     * 設定分數
     */
    public function setAction()
    {
        $tempArr = explode("-", $this->_getParam('classSn'));
        $grade = (int)$tempArr[0];
        $classSn = (int)$tempArr[1];
        $tempArr = explode("-", $this->_getParam('yearSemester'));
        $year = (int) $tempArr[0];
        $semester = (int) $tempArr[1];
        $stage = (int) $this->_getParam('stage');
        $subjectSn = $this->_getParam('subjectSn');
        $scores = $this->_getParam('score');



        //教師 sn
        $teacherSn = Teacher_Model_Teacher::getSnById();
        // 學期成績陣列
        $semesterArr = array();
        foreach ($scores as $test_kind=>$val) {
            $q = Doctrine_Query::create()
            ->from('Student_Model_StudentScoreStage a')
            ->where('subject_sn=?', $subjectSn)
            ->andWhere('class_sn=?', $classSn)
            ->andWhere('test_sort=?',$stage)
            ->andWhere('test_kind=?', $test_kind);
            if (!$res = $q->fetchOne()) {
                $scoreStage = new Student_Model_StudentScoreStage();
                $scoreStage->class_sn = $classSn;
                $scoreStage->subject_sn = $subjectSn;
                $scoreStage->test_kind = $test_kind;
                $scoreStage->test_sort = $stage;
                $scoreStage->sendmit = 'Y';
                $scoreStage->teacher_sn = $teacherSn;
                $scoreStage->save();
                $stageSn = $scoreStage->sn;
            }
            else
            $stageSn = $res->sn;


            foreach ($val as $studentSn=>$score) {
                $scoreStageDetail = new Student_Model_StudentScoreStageDetail();
                $find = $scoreStageDetail->getTable()
                ->findBySql('stage_sn=? AND student_sn=?',array($stageSn, $studentSn));
                if ($find->count()>0) {
                    $scoreStageDetail->assignIdentifier($find->getFirst()->sn);
                    //echo $find->getFirst()->sn; exit;
                }
                $scoreStageDetail->student_sn =  $studentSn;
                $scoreStageDetail->stage_sn = $stageSn;
                if ($score !=='')
                $scoreStageDetail->score = (float) $score;
                else
                $scoreStageDetail->score = NULL;

                $scoreStageDetail->teacher_sn = $teacherSn;
                $scoreStageDetail->save();

            }

        }

        // 考試設定資料
        $examine = new Semester_Model_SemesterExamine();
        $examineRes = $examine->getExaminSet($year, $semester, $grade);
        $ratio = $examineRes->ratio;

        // 各階段成績或全學期成績已完成計算
        if ($examineRes->period == count($scores) or
        $test_kind ==Semester_Model_SemesterExamine::WHOLE_SEMESTER_SCORE ) {
            $semesterScoreArr = array();
            $q = Doctrine_Query::create()
            ->select('a.student_sn , a.score, b.test_kind AS test_kind, b.test_sort AS test_sort')
            ->from ('Student_Model_StudentScoreStageDetail a')
            ->leftJoin('a.Student_Model_StudentScoreStage b')
            ->where('b.subject_sn=?',$subjectSn)
            ->andWhere('b.class_sn=?', $classSn)
            ->groupBy('a.student_sn, b.test_kind, b.test_sort');
            $res = $q->fetchArray();
            $totalRatio = 0;
            foreach($ratio as $val) {
                if (is_array($val))
                foreach($val as $vals)
                $totalRatio += $vals;
            }

            // 比率計算
            foreach($res as $row) {
                if ($row['test_kind'] == Semester_Model_SemesterExamine::WHOLE_SEMESTER_SCORE) // 全學期分數
                $semesterScoreArr[$row['student_sn']] = $row['score'];
                else {
                    if(!isset($semesterScoreArr[$row['student_sn']]))
                    $semesterScoreArr[$row['student_sn']] = 0;
                    $semesterScoreArr[$row['student_sn']] += ($ratio[$row['test_sort']][$row['test_kind']] / $totalRatio) * $row['score'] ;
                }
            }
            if ($semesterScoreArr) {
                foreach($semesterScoreArr as $studentSn=>$score) {
                    $studentScoreSemester =  new Student_Model_StudentScoreSemester() ;
                    $q = Doctrine_Query::create()
                    ->select('sn')
                    ->from('Student_Model_StudentScoreSemester')
                    ->where('student_sn=?', $studentSn )
                    ->andWhere('subject_sn=?', $subjectSn);
                    $sres = $q->fetchOne();
                    if ($sres)
                    $studentScoreSemester->assignIdentifier($sres->sn);
                    $studentScoreSemester->student_sn = $studentSn;
                    $studentScoreSemester->subject_sn = $subjectSn;
                    $studentScoreSemester->score = $score;
                    $studentScoreSemester->teacher_sn = $teacherSn;
                    $studentScoreSemester->save();
                }
            }
        }
        $this->_helper->json(1);
    }


    /**
     * 取得學科資料
     * @return unknown
     */
    protected function _getSubject()
    {
        $tempArr = explode("-", $this->_getParam('yearSemester'));
        $year = (int)$tempArr[0];
        $semester = (int)$tempArr[1];
        $tempArr = explode("-", $this->_getParam('classSn'));
        $grade = (int) $tempArr[0];
        $classSn = (int) $tempArr[1];
        // 學科資料
        $subject = new Semester_Model_SemesterSubject();
        $res = $subject->getSubject($year,$semester,$grade,$classSn);
        //Semester_Model_SemesterSubject::SCORE_MODE_STAGE);
        $arr = array();
        // print_r($res);
        foreach($res as $row) {
            foreach ($row as $val) {
                if ($val['scored'] == 'Y')
                $arr['subject'][$val['subject_sn']] = $val;
            }
        }
        // 考試設定資料
        $examine = new Semester_Model_SemesterExamine();
        $res = $examine->getExaminSet($year, $semester, $grade);
        $arr['examine'] = $res->toArray();
        return $arr;
    }


    /**
     * 取得分數
     */
    protected function _getScore()
    {
        $stage = (int)$this->_getParam('stage');
        $subjectSn = (int)$this->_getParam('subjectSn');
        $tempArr = explode("-", $this->_getParam('classSn'));
        $grade = (int)$tempArr[0];
        $classSn = (int) $tempArr[1];
        $tempArr = explode("-", $this->_getParam('yearSemester'));
        $year = (int)$tempArr[0];
        $semester = (int)$tempArr[1];
        if ($year and $semester and $grade and $classSn and $subjectSn and $stage ) {
            //   echo "$year and $semester and $grade and $classSn and $subjectSn and $stage";
            $q = Doctrine_Query::create()
            ->select('a.*, b.subject_sn as subject_sn, b.test_kind AS test_kind')
            ->from('Student_Model_StudentScoreStageDetail a')
            ->leftJoin('a.Student_Model_StudentScoreStage b')
            ->where('b.subject_sn=?', $subjectSn)
            ->andWhere('b.test_sort=?',$stage)
            ->andWhere('b.class_sn=?', $classSn);
            //          echo $q->getSqlQuery();
            $res = $q->fetchArray();
            $tempArr = array();
            foreach ($res  as $row) {
                $tempArr[$row['student_sn']][$row['test_kind']] = $row['score'];
            }
            $this->view->score = $tempArr;

            $student = new Student_Model_Student();
            $students = $student->getClassStudent($year, $semester, $grade, $classSn  );

            $this->view->students= $students;
        }
        else
        return false;
    }
}

